package cn.wit.summit.chwan.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.Stat.StatFactory;
import cn.wit.summit.chwan.adapters.RecommendAdapter;
import cn.wit.summit.chwan.adapters.RecommendSkeletonAdapter;
import cn.wit.summit.chwan.adapters.RecommendV2Adapter;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.db.NetResultCacheTable;
import cn.wit.summit.chwan.models.dbmanager.NetResultCacheManager;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.dto.JumpBaseBean;
import cn.wit.summit.chwan.models.dto.ViewBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.event.EnergyEvent;
import cn.wit.summit.chwan.models.response.IndexBeanV2Response;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.net.NetCallBack;
import cn.wit.summit.chwan.net.RpcConstant;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.activity.SearchActivity;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStrokeV2Big;
import cn.wit.summit.chwan.widgets.RecommendTopDownloadV2View;
import cn.wit.summit.chwan.widgets.RecommendTopWalletV2View;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener;
import cn.wit.summit.chwan.widgets.skeleton.Skeleton;
import cn.wit.summit.chwan.widgets.skeleton.SkeletonScreen;
import retrofit2.Retrofit;

/**
 * 推荐
 * Created by Alan on 2018/4/11.
 */

public class RecommendV2Fragment extends BaseFragment {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.notNetFl)
    FrameLayout notNetFl;
    @Bind(R.id.retryImg)
    ImageView retryImg;
    @Bind(R.id.retryText)
    TextView retryText;
    @Bind(R.id.recommendTopOneLl)
    LinearLayout recommendTopOneLl;
    @Bind(R.id.bar_title_tx)
    TextView barTitleTx;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.topTitle)
    RelativeLayout topTitle;
    @Bind(R.id.headerLl)
    LinearLayout headerLl;
    @Bind(R.id.recommendTopWallet)
    RecommendTopWalletV2View recommendTopWallet;
    @Bind(R.id.recommendTopDownload)
    RecommendTopDownloadV2View recommendTopDownload;
    @Bind(R.id.backSdv)
    SimpleDraweeView backSdv;

    private String TAG = "RecommendFragment";

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    private int pn = 1;
    private int totalDy = 0;

    private LinearLayoutManager layoutManager;
    private RecommendV2Adapter adapter;
    private List<RecommendV2Adapter.ViewBean> viewBeans = new ArrayList<>();

    private ControllerListener controllerListener;
    private Animatable mAnimatable;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recommend_v2, null);
        ButterKnife.bind(this, view);

        retrofitManager = RetrofitManager.getInstance(getActivity());
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        EventBus.getDefault().register(this);

        initView();
        initListView();
        initData();
        return view;
    }

    private void initView() {
        notNetFl.setVisibility(View.GONE);
        barTitleTx.setText(getResources().getString(R.string.title_home));
        back.setImageResource(R.mipmap.ic_main_top_search);
    }

    private void initListView() {
        adapter = new RecommendV2Adapter(getActivity(), viewBeans);
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                getIndexDataForFirst();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (pn == 1) pn += 1;
                getIndexData();
            }
        });
//        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                totalDy += dy;
//                setTopViewAlpha(totalDy);
//            }
//        });

        setTopViewAlpha(280);
    }

    private void setTopViewAlpha(int totalDy) {
        float alpha = totalDy / 280f;

        Drawable barBg = topTitle.getBackground();
        if (alpha == 0f) {
            barBg.setAlpha(0);
            barTitleTx.setAlpha(0f);
        } else if (alpha >= 1.0f) {
            barBg.setAlpha(255);
            barTitleTx.setAlpha(1f);
        } else {
            barBg.setAlpha((int) (alpha * 255));
            barTitleTx.setAlpha(alpha);
        }
        topTitle.setBackgroundDrawable(barBg);
    }

    private NetResultCacheTable table = null;

    private void initData() {
        try {
            Map<String, String> tempMap = new HashMap<>();
            tempMap.put("pn", pn + "");
            String requestStr = new Gson().toJson(tempMap);
            table = NetResultCacheManager.getInstance().getDataByUrl(RpcConstant.forumRootUrl + RpcConstant.homePageV2, requestStr);
            if (table != null && !StringUtils.isEmpty(table.getResponseStr())) {
                hideSkeleton();
                String data = table.getResponseStr();
                ResponseBase<IndexBeanV2Response> temp = fromJsonObject(data, IndexBeanV2Response.class);
                updataUi(temp.getData_info());
            } else {
                initSkeleton();
                showSkeleton();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        getIndexDataForFirst();
    }

    private void getIndexDataForFirst() {
        refreshLayout.setEnableLoadMore(true);
        pn = 1;
        getIndexData();
    }

    public <T> ResponseBase<T> fromJsonObject(String reader, Class<T> clazz) {
        Type type = new NetCallBack.ParameterizedTypeImpl(ResponseBase.class, new Class[]{clazz});
        return new Gson().fromJson(reader, type);
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.e(TAG + " onResume()");
        changeLoginStatus();
        changeTopStatus();
        StatFactory.getInstance().sendVistPage(getActivity(), "Index", "Index");

        boolean isClick = PreferenceUtil.getBoolPreferences(getActivity(), PreferenceUtil.PRE_SEARCH_IS_CILICK);
        if (isClick) {
            back.setVisibility(View.VISIBLE);
            backSdv.setVisibility(View.GONE);
            handler.removeMessages(1);
        } else {
            if (controllerListener==null) {
                controllerListener = new BaseControllerListener<ImageInfo>() {
                    @Override
                    public void onFinalImageSet(
                            String id,
                            @Nullable ImageInfo imageInfo,
                            @Nullable Animatable anim) {
                        mAnimatable = anim;
                        handler.removeMessages(1);
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                };
            }

            back.setVisibility(View.GONE);
            backSdv.setVisibility(View.VISIBLE);
            Uri uri = Uri.parse("asset:///aaa.gif");
            DraweeController draweeController = Fresco.newDraweeControllerBuilder().setUri(uri)
//                    .setAutoPlayAnimations(true) // 设置加载图片完成后是否直接进行播放
                    .setControllerListener(controllerListener)
                    .build();
            backSdv.setController(draweeController);
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (mAnimatable!=null) {
                        mAnimatable.stop();
                        mAnimatable.start();
                        handler.removeMessages(1);
                        Message mess = new Message();
                        mess.what = 1;
                        handler.sendMessageDelayed(mess, 2500);
                    }
                    break;
            }
        }
    };

    private void changeLoginStatus() {
        recommendTopWallet.initTotalWalletNum();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EnergyEvent energyEvent) {
        if (recommendTopWallet != null) {
            recommendTopWallet.initTotalWalletNum();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        changeLoginStatus();
        changeTopStatus();
        LogUtils.e(TAG + " onHiddenChanged():" + hidden);
    }

    private void changeTopStatus() {
        try {
            if (recommendTopDownload != null) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (recommendTopDownload != null) {
                            recommendTopDownload.setTotalDownloadNum();
                        }
                    }
                }, 200);
            }
        } catch (Exception e) {
        }
    }

    List<ViewBean> mDatasSkeleton = new ArrayList<>();
    private SkeletonScreen skeletonScreen;

    private void initSkeleton() {
        RecommendSkeletonAdapter skeletonAdapter = new RecommendSkeletonAdapter(getActivity(), mDatasSkeleton);
        mDatasSkeleton.add(new ViewBean(RecommendAdapter.ViewType.TYPE_PAST_IMAGE.ordinal(), null));
        mDatasSkeleton.add(new ViewBean(RecommendAdapter.ViewType.TYPE_NEW_GAME.ordinal(), null));
        mDatasSkeleton.add(new ViewBean(RecommendAdapter.ViewType.TYPE_BEST_MONTH.ordinal(), null));

        skeletonScreen = Skeleton.bind(recyclerView)
                .adapter(adapter)
                .adapter(skeletonAdapter)
                .shimmer(true)
                .color(R.color.shimmer_color)
                .angle(20)
                .duration(1200).show();
    }

    private void hideSkeleton() {
        if (skeletonScreen == null) return;
        skeletonScreen.hide();
    }

    private void showSkeleton() {
        if (skeletonScreen == null) return;
        skeletonScreen.show();
    }

    private void getIndexData() {
        int uId = 0;
        AccountBean accountBean = AccountUtil.getInstance().getAccountData();
        if (accountBean != null) {
            uId = AccountUtil.getInstance().getUid();
        }
        api.getIndexDataV2(uId, pn).enqueue(new MyCallback<ResponseBase<IndexBeanV2Response>>() {
            @Override
            public void onSuccess(ResponseBase<IndexBeanV2Response> model) {
                if (pn == 1) {
                    Gson gson = new Gson();
                    Map<String, String> tempMap = new HashMap<>();
                    tempMap.put("pn", pn + "");
                    String requestStr = gson.toJson(tempMap);
                    String retStr = gson.toJson(model);
                    String retUrl = RpcConstant.forumRootUrl + RpcConstant.homePageV2;
                    LogUtils.e("retUrl:" + retUrl + "\nrequestStr:" + requestStr + "\nretStr:" + retStr);
                    NetResultCacheManager.getInstance().insertData(retUrl, requestStr, retStr);
                }

                IndexBeanV2Response data = model.getData_info();
                hideSkeleton();
                updataUi(data);
            }

            @Override
            public void onFailure(int code, String msg) {
                showToast(msg);
                try {
                    refreshLayout.finishLoadMore();
                    if (viewBeans.size() == 0) {
                        if (code == -3) {
                            notNetFl.setVisibility(View.VISIBLE);
                            refreshLayout.setVisibility(View.GONE);
                        }
//                        if (pn == 1) {
                        refreshLayout.finishRefresh();
//                        } else {
//                            refreshLayout.setEnableLoadMore(false);
//                        }
                        hideSkeleton();
                    } else {
//                        if (pn == 1) {
                        refreshLayout.finishRefresh();
//                        } else {
//                            refreshLayout.finishLoadMoreWithNoMoreData();
//                        }
                        hideSkeleton();
                    }
                } catch (Exception e) {
                    if (viewBeans.size() == 0) {
                        if (code == -3) {
                            notNetFl.setVisibility(View.VISIBLE);
                        }
                        hideSkeleton();
                    } else {
                        hideSkeleton();
                    }
                    e.printStackTrace();
                }
            }
        });
    }

    private void updataUi(IndexBeanV2Response data) {
        if (data == null) {
            return;
        } else {
            if (notNetFl != null)
                notNetFl.setVisibility(View.GONE);
            if (refreshLayout != null)
                refreshLayout.setVisibility(View.VISIBLE);
        }
        if (pn == 1) {
            viewBeans.clear();
            adapter.clearTempData();

//            viewBeans.add(new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TOP));
        }

        RecommendV2Adapter.ViewBean lineView = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_LINE_22);

        JumpBaseBean banner = data.getRecommend_banner();
        if (banner != null && banner.getGame_list() != null && banner.getGame_list().size() > 0) {
            if (viewBeans.size() > 0)
                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_CRACK_GAME, banner);
            viewBeans.add(viewBean);
        }

        //分页数据
        List<JumpBaseBean> bannerList = data.getRecommend_banner_list();
        for (int i = 0; bannerList != null && i < bannerList.size(); i++) {
            JumpBaseBean tempBanner = bannerList.get(i);
            if (tempBanner.getGame_list() != null && tempBanner.getGame_list().size() > 0) {
                if (viewBeans.size() > 0)
                    viewBeans.add(lineView);
                if (tempBanner != null && tempBanner.getGame_list() != null && tempBanner.getGame_list().size() > 0) {
                    RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_CRACK_GAME, tempBanner);
                    viewBeans.add(viewBean);
                }
            }
        }

        JumpBaseBean dailyNew = data.getRecommend_edn();
        if (dailyNew != null && dailyNew.getGame_list() != null && dailyNew.getGame_list().size() > 0) {
            if (viewBeans.size() > 0)
                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean titleView = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TITLE_ONE, dailyNew);
            viewBeans.add(titleView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_DAILY_NEW, dailyNew);
            viewBeans.add(viewBean);
        }

        JumpBaseBean gameStarter = data.getRecommend_tf();
        if (gameStarter != null && gameStarter.getGame_list() != null && gameStarter.getGame_list().size() > 0) {
            if (viewBeans.size() > 0)
                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean titleView = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TITLE_ONE, gameStarter);
            viewBeans.add(titleView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_GAME_STARTER, gameStarter);
            viewBeans.add(viewBean);
        }

        JumpBaseBean greatCrack = data.getRecommend_game_list_v1();
        if (greatCrack != null && greatCrack.getGame_list() != null && greatCrack.getGame_list().size() > 0) {
            if (viewBeans.size() > 0)
                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_GREAT_CRACK, greatCrack);
            viewBeans.add(viewBean);
        }

        JumpBaseBean gameHot = data.getNet_hot_game();
        if (gameHot != null && gameHot.getGame_list() != null && gameHot.getGame_list().size() > 0) {
            if (viewBeans.size() > 0)
                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean titleView = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TITLE_ONE, gameHot);
            viewBeans.add(titleView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_GAME_HOT, gameHot);
            viewBeans.add(viewBean);
        }

        JumpBaseBean greatCrackV2 = data.getRecommend_game_list_v2();
        if (greatCrackV2 != null && greatCrackV2.getGame_list() != null && greatCrackV2.getGame_list().size() > 0) {
            if (viewBeans.size() > 0)
                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_GREAT_CRACK, greatCrackV2);
            viewBeans.add(viewBean);
        }

        JumpBaseBean MediaTest = data.getMedia_test();
        if (MediaTest != null && MediaTest.getGame_list() != null && MediaTest.getGame_list().size() > 0) {
            if (viewBeans.size() > 0)
                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean titleView = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TITLE_ONE, MediaTest);
            viewBeans.add(titleView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_GAME_HOT, MediaTest);
            viewBeans.add(viewBean);
        }

        adapter.notifyDataSetChanged();
        if (refreshLayout != null) {
            if (pn != 1 && (data == null || data.getRecommend_banner_list() == null
                    || data.getRecommend_banner_list().size() == 0)) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                if (pn == 1)
                    refreshLayout.finishRefresh();
                else
                    refreshLayout.finishLoadMore();
                pn += 1;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {
        recommendTopDownload.setTotalDownloadNum();//设置下载数

        String str = adapter.getPoByGameId(downloadEvent.getGameId());
        if (!StringUtils.isEmpty(str)) {
            GameListBaseBean bean = adapter.getBeanData(Integer.valueOf(str), 0);
            if (bean == null) return;
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }

            View view = layoutManager.findViewByPosition(Integer.valueOf(str));

            DownloadViewStrokeV2Big dowView = view.findViewById(R.id.itemCrackGameBt);
            if (dowView != null) {
                dowView.updateButn(table);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.notNetFl, R.id.back, R.id.backSdv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.backSdv:
                PreferenceUtil.saveBoolPreference(getActivity(), PreferenceUtil.PRE_SEARCH_IS_CILICK, true);
            case R.id.back:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                getActivity().overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
                break;
            case R.id.notNetFl:
                if (table == null)
                    showSkeleton();
                notNetFl.setVisibility(View.GONE);
                refreshLayout.setVisibility(View.VISIBLE);
                refreshLayout.autoRefresh();
                getIndexData();
                break;
        }
    }
}
